package servlets;

import dao.JdbcRoleDao;
import dao.JdbcUserDao;
import entries.Role;
import entries.User;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.sql.SQLException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class EditUser extends Dispatcher {

    private final static Log LOGGER = LogFactory.getLog(EditUser.class);

    protected void doGet(HttpServletRequest request,
                         HttpServletResponse response) throws ServletException, IOException {
        String login = request.getParameter("login");
        HttpSession session = request.getSession();
        JdbcUserDao userDao = new JdbcUserDao();

        User user = null;
        try {
            user = userDao.findByLogin(login);
            if (user == null) {
                response.sendRedirect("/login.jsp");
                session.invalidate();
                return;
            } else {
                request.setAttribute("user", user);
                this.forward("/editUser.jsp", request, response);
                return;
            }
        } catch (Exception e) {
            LOGGER.error("Exception", e);
            throw new RuntimeException(e);
        }
    }

    protected void doPost(HttpServletRequest request,
                          HttpServletResponse response) throws ServletException, IOException {

        response.setContentType("text/html");
        JdbcUserDao userDao = new JdbcUserDao();

        long id = Long.parseLong(request.getParameter("id"));
        String login = request.getParameter("login");
        String password = request.getParameter("password");
        String passwordAgain = request.getParameter("passwordagain");

        if (password.equals(passwordAgain)) {

            String email = request.getParameter("email");
            String firstName = request.getParameter("firstname");
            String lastName = request.getParameter("lastname");
            String birhday = request.getParameter("birth");
            String role = request.getParameter("role");

            Date date = null;
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");

            try {
                date = format.parse(birhday);

            } catch (ParseException e) {
                LOGGER.error("ParseException", e);
                throw new RuntimeException(e);
            }
            java.sql.Date sqlDate = new java.sql.Date(date.getTime());

            User user = new User();
            user.setId(id);
            user.setLogin(login);
            user.setPassword(password);
            user.setEmail(email);
            user.setFirstName(firstName);
            user.setLastName(lastName);
            user.setBirthDay(sqlDate);

            JdbcRoleDao roleDao = new JdbcRoleDao();
            Role roleUser = roleDao.findByName(role);
            user.setRole(roleUser);

            try {
                userDao.update(user);
            } catch (SQLException e) {
                LOGGER.error("SQLException", e);
                throw new RuntimeException(e);
            } catch (ClassNotFoundException e) {
                LOGGER.error("ClassNotFoundException", e);
                throw new RuntimeException(e);
            }
        }

        List<User> list = new ArrayList<User>();
        try {
            list = userDao.findAll();
        } catch (SQLException e) {
            LOGGER.error("SQLException", e);
            throw new RuntimeException(e);
        } catch (ClassNotFoundException e) {
            LOGGER.error("ClassNotFoundException", e);
            throw new RuntimeException(e);
        }

        request.setAttribute("users", list);
        this.forward("/adminPage.jsp", request, response);
        return;
    }
}
